package org.example.maven.service.Impl;

import org.example.maven.mapper.departmentMapper;
import org.example.maven.pojo.department.list.AddDepartment;
import org.example.maven.pojo.department.list.DepartmentAllDetail;
import org.example.maven.pojo.department.list.DepartmentListTable;
import org.example.maven.pojo.department.list.DepartmentSelect;
import org.example.maven.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class departmentServiceImpl implements DepartmentService {
    @Autowired
    private departmentMapper departmentMapper;

    // 公共树构建方法
    private List<DepartmentListTable> buildDepartmentTree(List<DepartmentAllDetail> departments,
                                                          Function<List<DepartmentListTable>, Integer> rootFinder) {
        Map<Integer, DepartmentListTable> nodeMap = new HashMap<>();

        // 1. 创建所有节点并建立映射
        departments.forEach(dept -> {
            Integer id = Integer.parseInt(dept.getId());
            nodeMap.put(id, convertToTreeNode(dept));
        });

        // 2. 建立父子关系
        nodeMap.values().forEach(node -> {
            Integer parentId = Integer.parseInt(node.getParentId());
            DepartmentListTable parent = nodeMap.get(parentId);
            if (parent != null) {
                parent.getChildren().add(node);
            }
        });

        // 3. 确定根节点
        List<DepartmentListTable> nodes = new ArrayList<>(nodeMap.values());
        Integer rootParentId = rootFinder.apply(nodes);

        // 4. 处理根节点：当 parentId=0 时，替换为自身的 id
        List<DepartmentListTable> rootNodes = nodes.stream()
                .filter(node -> Integer.parseInt(node.getParentId()) == rootParentId)
                .peek(node -> {
                    if (rootParentId == 0) {  // 仅当根父ID为0时替换
                        node.setParentId(node.getId());  // 直接修改父ID为当前节点ID
                    }
                })
                .collect(Collectors.toList());

        return rootNodes;
    }

    // 实体转换方法
    private DepartmentListTable convertToTreeNode(DepartmentAllDetail dept) {
        return new DepartmentListTable(
                dept.getId(),
                dept.getDeptName(),
                dept.getStatus(),
                dept.getCreateTime(),
                dept.getParentId(),
                dept.getRealName()
        );
    }

    @Override
    public List<DepartmentListTable> getAllDepartmentList() {
        return buildDepartmentTree(departmentMapper.getAllDepartmentList(),
                nodes -> 0); // 固定根节点为0
    }

    @Override
    public List<DepartmentListTable> getSpecieDepartment(String deptName, Integer status) {
        List<DepartmentAllDetail> departments = departmentMapper.getSpecieDepartment(deptName, status);

        return buildDepartmentTree(departments,
                nodes -> nodes.stream()
                        .mapToInt(node -> Integer.parseInt(node.getParentId()))
                        .min()
                        .orElse(0)); // 动态查找最小parentId
    }

    @Override
    public List<DepartmentSelect> getDepartmentSelect() {
        List<DepartmentAllDetail> list = departmentMapper.getAllDepartmentList();
        Map<String, DepartmentSelect> nodeMap = new LinkedHashMap<>();  // 改用有序Map
        Map<String, List<DepartmentSelect>> parentChildMap = new HashMap<>();
        final String[] rootKey = new String[1];

        // 第一阶段：构建基础数据结构
        for (DepartmentAllDetail d : list) {
            // 创建节点对象（避免重复创建）
            DepartmentSelect node = nodeMap.computeIfAbsent(d.getId(), k ->
                    new DepartmentSelect(d.getDeptName(), d.getId())
            );

            // 按父ID分组子节点
            parentChildMap.computeIfAbsent(d.getParentId(), k -> new ArrayList<>())
                    .add(node);

            // 直接标记根节点（parentId为0的节点）
            if ("0".equals(d.getParentId())) {
                rootKey[0] = d.getId();
            }
        }

        // 第二阶段：建立父子关系（O(n)复杂度）
        parentChildMap.forEach((parentId, children) -> {
            DepartmentSelect parentNode = nodeMap.get(parentId);
            if (parentNode != null) {
                parentNode.setChildren(children);  // 建议在DepartmentSelect中添加setChildren方法
            }
        });

        // 第三阶段：返回结果
        List<DepartmentSelect> result = new ArrayList<>();
        if (rootKey[0] != null) {
            result.add(nodeMap.get(rootKey[0]));
        }
        return result;
    }

    @Override
    public void addDepartment(AddDepartment addDepartment) {
        departmentMapper.addDepartment(addDepartment);
    }

    @Override
    public AddDepartment getDepartmentById(Integer id) {
        AddDepartment addDepartment=departmentMapper.getDepartmentById(id);
        if(addDepartment.getParentId().equals("0")){
            addDepartment.setParentId(addDepartment.getId());
        }
        return addDepartment;
    }

    @Override
    public void updateDepartmentById(AddDepartment addDepartment) {
        departmentMapper.updateDepartmentById(addDepartment);
    }

    @Override
    public void deleteDepartment(Integer id) {
        departmentMapper.deleteDepartment(id);
    }

    @Override
    public AddDepartment findDepartmentByName(String deptName) {
        return departmentMapper.findDepartmentByName(deptName);
    }

    @Override
    public AddDepartment findDepartmentIsDeleted(String deptName) {
        return departmentMapper.findDepartmentIsDelete(deptName);
    }

    @Override
    public void updateDeletedDepartment(AddDepartment addDepartment) {
        departmentMapper.updateDeletedDepartment(addDepartment);
    }
}
